package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * Redis自增
 * @author Zeng
 * @date 2024/4/22
 */
@Slf4j
@Component
public class RedisIdWorker {
    /**
     * 开始时间戳
     */
    private static final long START_TIMESTAMP = 1640995200000L;

    private static final int COUNT_BITS = 32;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成全局唯一ID(Redis自增)
     * @param keyPrefix
     * @return
     */
    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        // 1.1 获取当前日期的毫秒值
        Long nowSecond = now.toEpochSecond(java.time.ZoneOffset.UTC);
        long timestamp=nowSecond-START_TIMESTAMP;
        //2.生成序列号
        //2.1 获取当前日期，精确到天
        String date = now.format(java.time.format.DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //increment:是Redis自增长
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        log.info("timestamp:{},increment:{}",timestamp,increment);
        //拼接并返回
        return timestamp << COUNT_BITS | increment;

    }
}
